package com.xyz.eduservice.controller.front;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xyz.client.UcenterClient;
import com.xyz.entity.R;
import com.xyz.vo.UcenterMemberInfoCommonVo;
import com.xyz.utils.JwtUtil;
import com.xyz.eduservice.entity.EduComment;
import com.xyz.eduservice.service.EduCommentService;


import io.swagger.v3.oas.annotations.media.Schema;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import jakarta.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 前台评论控制器
 * @author zsr
 * @date 2021/6/22 17:21
 */
@Schema(description="前台评论接口")
//@CrossOrigin
@RestController
@RequestMapping("/eduservice/commentfront")
public class CommentController {

    @Autowired
    private EduCommentService commentService;
    @Autowired
    private UcenterClient ucenterClient;

    //根据课程id查询评论列表
    @Schema(description="评论分页列表")
    @GetMapping("{page}/{limit}")
    public R index(
            @Schema(name = "page", description = "当前页码", required = true)
            @PathVariable Long page,

            @Schema(name = "limit", description = "每页记录数", required = true)
            @PathVariable Long limit,

            @Schema(name = "courseQuery", description = "查询对象", required = false)
                    String courseId) {
        Page<EduComment> pageParam = new Page<>(page, limit);

        QueryWrapper<EduComment> wrapper = new QueryWrapper<>();
        wrapper.eq("course_id",courseId);
        wrapper.orderByDesc("gmt_create");

        commentService.page(pageParam,wrapper);
        List<EduComment> commentList = pageParam.getRecords();

        Map<String, Object> map = new HashMap<>();
        map.put("items", commentList);
        map.put("current", pageParam.getCurrent());
        map.put("pages", pageParam.getPages());
        map.put("size", pageParam.getSize());
        map.put("total", pageParam.getTotal());
        map.put("hasNext", pageParam.hasNext());
        map.put("hasPrevious", pageParam.hasPrevious());
        return R.ok().data(map);
    }

    //2. 添加评论
    @Schema(description="添加评论")
    @PostMapping("auth/save")
    public R save(@RequestBody EduComment comment, HttpServletRequest request) {
        String memberId = JwtUtil.getMemberIdByJwtToken(request);
        if(StringUtils.isEmpty(memberId)) {
            return R.error().code(28004).message("请登录");
        }
        comment.setMemberId(memberId);
        //TODO 考虑不写入昵称和头像 连表查询
        UcenterMemberInfoCommonVo ucenterInfo = ucenterClient.getInfo(memberId);
        comment.setNickname(ucenterInfo.getNickname());
        comment.setAvatar(ucenterInfo.getAvatar());

        commentService.save(comment);
        return R.ok();
    }


}
